<template>
  <div>
    <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="100px">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type" @change="clickRadio">
          <el-radio  v-for="(type, index) in dataForm.typeList" :label="index" :key="index">{{ type
            }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="对应课程" prop="side">
          <el-select v-model="dataForm.side" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item :label="dataForm.typeList[dataForm.type] + '名称'" prop="courseTitle">
        <el-input v-model="dataForm.courseTitle" :placeholder="dataForm.typeList[dataForm.type] + '名称'"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type==0" label="封面图片">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentName">
        <el-popover
          ref="courseListPopover"
          placement="bottom-start"
          trigger="click"
          v-model="popoverVisible">
          <el-tree
            :data="courseList"
            :props="courseTreeProps"
            node-key="courseId"
            ref="courseListTree"
            @current-change="courseTreeCurrentChangeHandle"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:courseListPopover :readonly="true" placeholder="点击选择上级菜单"
                  class="menu-list__input"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type != 1" label="排序号" prop="orderNum">
        <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false ,imageUrl=''">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
  
  </div>
</template>

<script>
  import {treeDataTranslate} from '@/utils'
  import Icon from '@/icons'

  export default {
    data () {
      var validateUrl = (rule, value, callback) => {
        if (this.dataForm.type === 1 && !/\S/.test(value)) {
          callback(new Error('菜单URL不能为空'))
        } else {
          callback()
        }
      }
      return {
        popoverVisible: false,
        options: [{
          value: 0,
          label: '教师课程'
        },{
          value: 1,
          label: '学生课程'
        }],
        dialogTableVisible: true,
        visible: false,
        imageUrl: '',
        url: '',
        dataForm: {
          courseId: 0,
          type: 0,
          typeList: ['课程', '上下册', '栏目'],
          courseTitle: '',
          fId: 0,
          parentName: '',
          courseImgs: '',
          orderNum: 0,
          icon: '',
          side: 0
        },
        dataRule: {
          courseTitle: [
            {required: true, message: '标题名称不能为空', trigger: 'blur'}
          ],
          parentName: [
            {required: true, message: '上级菜单不能为空', trigger: 'change'}
          ],
          url: [
            {validator: validateUrl, trigger: 'blur'}
          ]
        },
        courseList: [],
        courseTreeProps: {
          label: 'courseTitle',
          children: 'children'
        }
      }
    },
    created () {
      this.iconList = Icon.getNameList()
    },
    methods: {
      init (id) {
        this.imageUrl = ''
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.dataForm.courseId = id || 0
        this.$http({
          url: this.$http.adornUrl('/admin/course/all/courseList'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          data.list.push({
            courseId: 0,
            courseTitle: '一级菜单',
            fId: -1
          })
          this.courseList = treeDataTranslate(data.list, 'courseId', 'fId')
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (!this.dataForm.courseId) {
            // 新增
            this.courseListTreeSetCurrentNode()
          } else {
            // 修改
            this.$http({
              url: this.$http.adornUrl(`/admin/course/info/${this.dataForm.courseId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              this.dataForm.side = data.course.side
              this.dataForm.courseId = data.course.courseId
              this.dataForm.type = data.course.type
              this.dataForm.courseTitle = data.course.courseTitle
              this.dataForm.fId = data.course.fId
              this.dataForm.courseImgs = data.course.courseImgs
              this.imageUrl = data.course.courseImgs
              this.dataForm.orderNum = data.course.orderNum
              this.courseListTreeSetCurrentNode()
            })
          }
        })
      },
      // 菜单树选中
      courseTreeCurrentChangeHandle (data, node) {
        console.log(this.dataForm.type)
        if (data._level !== this.dataForm.type + 1) {
          this.$message.warning('请选择对应目录')
          return false
        }
        this.dataForm.fId = data.courseId
        this.dataForm.parentName = data.courseTitle
        this.popoverVisible = !this.popoverVisible
      },
      // 菜单树设置当前选中节点
      courseListTreeSetCurrentNode () {
        this.$refs.courseListTree.setCurrentKey(this.dataForm.fId)
        this.dataForm.parentName = (this.$refs.courseListTree.getCurrentNode() || {})['courseTitle']
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/admin/course/${!this.dataForm.courseId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'courseId': this.dataForm.courseId || undefined,
                'type': this.dataForm.type,
                'courseTitle': this.dataForm.courseTitle,
                'fId': this.dataForm.fId,
                'courseImgs': this.dataForm.courseImgs,
                'orderNum': this.dataForm.orderNum,
                'side': this.dataForm.side
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      handleAvatarSuccess (res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        if (res && res.code === 0) {
          if (this.num === this.successNum) {
            this.$message.success('上传成功')
            this.dataForm.courseImgs = res.url
          }
        } else {
          this.$message.error(res.msg)
        }
      },
      beforeAvatarUpload (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
      },
      clickRadio (type) {
        this.$refs['dataForm'].resetFields()
        this.dataForm.type=type
        this.dataForm.parentName = ''
        this.dataForm.courseImgs = ''
        this.imageUrl=''
        if (type === 0) {
          this.dataForm.parentName = '一级菜单'
          this.dataForm.fId = 0
        }
      }
    }
  }
</script>

<style lang="scss">
  .mod-menu {
    .menu-list__input,
    .icon-list__input {
      > .el-input__inner {
        cursor: pointer;
      }
    }

    &__icon-popover {
      width: 458px;
      overflow: hidden;
    }

    &__icon-inner {
      width: 478px;
      max-height: 258px;
      overflow-x: hidden;
      overflow-y: auto;
    }

    &__icon-list {
      width: 458px;
      padding: 0;
      margin: -8px 0 0 -8px;

      > .el-button {
        padding: 8px;
        margin: 8px 0 0 8px;

        > span {
          display: inline-block;
          vertical-align: middle;
          width: 18px;
          height: 18px;
          font-size: 18px;
        }
      }
    }

    .icon-list__tips {
      font-size: 18px;
      text-align: center;
      color: #e6a23c;
      cursor: pointer;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
